//
//  TestDownloadController.m
//  ProjectDemo
//
//  Created by IOS3 on 2019/1/8.
//  Copyright © 2019 IOS3. All rights reserved.
//

#import "TestDownloadController.h"
#import "MCDownloader.h"
#import <YYModel.h>
#import "TestDownloadCell.h"


@interface TestDownloadController ()
@property (nonatomic, copy) NSArray *downloadURLs;
@end

@implementation TestDownloadController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColor.whiteColor;
    
    
//     [self testDownloadOne];
    

//    [self testFileManager];
    [self setupUI];
    
}


- (void)setupUI {
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView = tableView;
    [self.tableView registerNib:[UINib nibWithNibName:@"TestDownloadCell" bundle:nil] forCellReuseIdentifier:NSStringFromClass(TestDownloadCell.class)];
}



#pragma mark - tableView delegate & datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.downloadURLs.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TestDownloadCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(TestDownloadCell.class) forIndexPath:indexPath];
    NSString *url = self.downloadURLs[indexPath.row];
    cell.url = url;
    return cell;
}









- (NSArray *)downloadURLs {
    if (!_downloadURLs) {
        NSMutableArray *marr = [NSMutableArray array];
        
        NSString *jsonPath = [NSBundle.mainBundle pathForResource:@"downloadSource" ofType:@"json"];
        NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
        id obj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
        if ([obj isKindOfClass:NSArray.class]) {
            NSArray *array = (NSArray *)obj;
            for (NSString *urlString in array) {
                [marr addObject:urlString];
            }
        }
        _downloadURLs = marr.copy;
    }
    return _downloadURLs;
}





- (void)testFileManager {
    NSString *path = @"/Users/ios3/Desktop/testFile/test";
    NSFileManager *manager = [NSFileManager defaultManager];

    
    NSString *path1 = [[[path stringByAppendingPathComponent:@"dir"] stringByAppendingPathComponent:@"test"] stringByAppendingPathComponent:@"yyy"];
    
    
    BOOL result = [manager fileExistsAtPath:path1];
    if (!result) {
        DLog(@"directory not exists");
        [manager createDirectoryAtPath:path1 withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *path2 = [[[path stringByAppendingPathComponent:@"dir"] stringByAppendingPathComponent:@"test2"] stringByAppendingPathComponent:@"xxx"];
    if (![manager fileExistsAtPath:path2]) {
        [manager createDirectoryAtPath:path2 withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    path1 = [path1 stringByAppendingPathComponent:@"Contents.json"];
    if ([manager fileExistsAtPath:path1]) {
        NSError *error = nil;
        path2 = [path2 stringByAppendingPathComponent:@"Contents.json"];
        [manager moveItemAtPath:path1 toPath:path2 error:&error];
        if (error) {
            DLog(@"移动失败, %@",error);
        }
    }
}





- (void)testDownloadOne {
    
    NSString *jsonPath = [NSBundle.mainBundle pathForResource:@"downloadSource" ofType:@"json"];
    NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
    id obj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
    if ([obj isKindOfClass:NSArray.class]) {
        NSArray *array = (NSArray *)obj;
        for (NSString *urlString in array) {
            // DLog(@"url: %@", urlString);
            NSURL *url = [NSURL URLWithString:urlString];
            [self downloadWithURL:url];
        }
    }
    
}

- (void)downloadWithURL:(NSURL *)url {
    
    
    [[MCDownloader sharedDownloader] downloadDataWithURL:url progress:^(NSInteger receivedSize, NSInteger expectedSize, NSInteger speed, NSURL * _Nullable targetURL) {
        
        DLog(@"receivedSize: %ld, expectedSize: %ld, speed: %ld, targetURL: %@", receivedSize, expectedSize, speed, targetURL);
        
    } completed:^(MCDownloadReceipt * _Nullable receipt, NSError * _Nullable error, BOOL finished) {
        
        DLog(@"filePath: %@", receipt.filePath);
        DLog(@"receipt.filename: %@", receipt.filename);
        DLog(@"receipt.truename: %@", receipt.truename);
        DLog(@"________finished: %@", finished ? @"true" : @"false");
        
        if (finished) {
            NSError *error = nil;
            
            
            NSString *newPath = [self getTargetPathWith:receipt.truename];
            
            [[NSFileManager defaultManager] moveItemAtPath:receipt.filePath toPath:newPath error:&error];
            if (error) {
                DLog(@"文件移动失败, error: %@", error);
            }
        }
        
        
    }];
}

- (NSString *)getTargetPathWith:(NSString *)fileName {
    NSString *path =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    path = [path stringByAppendingPathComponent:@"book"];
    
    BOOL flag = [[NSFileManager defaultManager] fileExistsAtPath:path];
    if (!flag) {
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    path = [path stringByAppendingPathComponent:fileName];
    
    return path;
}



/*
 
 */




@end
